package com.btpj.shop.service.impl;

import com.btpj.shop.dao.CategoryMapper;
import com.btpj.shop.dto.CategoryDto;
import com.btpj.shop.dto.param.CategoryParam;
import com.btpj.shop.entity.Category;
import com.btpj.shop.entity.User;
import com.btpj.shop.service.CategoryService;
import com.btpj.shop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private UserService userService;

    @Transactional
    @Override
    public boolean addCategory(CategoryParam categoryParam) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryParam, category);
        User currentUser = userService.getUserInfo();
        category.setCreateUser(currentUser.getId());
        category.setUpdateUser(currentUser.getId());
        return categoryMapper.insertSelective(category) > 0;
    }

    @Override
    public List<CategoryDto> getCategoryDtoList(Long parentId) {
        return categoryMapper.selectByParentId(parentId).stream().map(Category::category2Dto).collect(Collectors.toList());
    }

    @Override
    public boolean exists(Long id) {
        return categoryMapper.selectByPrimaryKey(id) != null;
    }

    @Override
    public CategoryDto getCategoryDto(Long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        return category.category2Dto();
    }

    @Transactional
    @Override
    public boolean updateCategory(Long id, @NotBlank String name, @NotNull Integer sort) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        category.setName(name);
        category.setSort(sort);
        category.setUpdateUser(userService.getUserInfo().getId());
        return categoryMapper.updateByPrimaryKey(category) > 0;
    }

    @Transactional
    @Override
    public boolean deleteCategories(Long[] ids) {
        return categoryMapper.deleteByIds(ids) > 0;
    }
}
